package cn.edu.zhku.aspect;

import cn.edu.zhku.aspect.annotation.CheckFormExist;
import cn.edu.zhku.constant.ResponseCode;
import cn.edu.zhku.dto.BaseDto;
import cn.edu.zhku.service.FormService;
import cn.edu.zhku.util.PojoUtil;
import cn.edu.zhku.util.ResultUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Order(1)
public class CheckFormExistAspect extends BaseDtoAspect {

    @Autowired
    private FormService formService;

    @Pointcut("@annotation(cn.edu.zhku.aspect.annotation.CheckFormExist)")
    public void pointcut() {}

    @Around("baseDtoPointcut() && pointcut()")
    public Object checkFormExist(ProceedingJoinPoint joinPoint) throws Throwable {
        CheckFormExist checkFormExist = ((MethodSignature) joinPoint.getSignature())
                .getMethod().getAnnotation(CheckFormExist.class);
        String value = checkFormExist.value();
        BaseDto baseDto = (BaseDto) joinPoint.getArgs()[0];
        if (PojoUtil.form.notExistForm(formService, baseDto.getFormId()))
            return ResultUtil.getResult(ResponseCode.conflict, value);
        return joinPoint.proceed();
    }

}
